package com.zx.mobile.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zx.map.utils.SUConstants;
import com.zx.platform.utils.AlipayUtil;
import com.zx.platform.utils.HttpClientCommon;
import com.zx.platform.utils.StrUtils;
import com.zx.scp.utils.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.MerchantOfflineConfigInfoService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.MerchantOfflineConfigInfoModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.wx.WxOauthHelper;
import com.zx.mobile.domain.offline.OfflineNotifyChangeDomain;
import com.zx.mobile.service.proxy.IncomePayProxy;
import com.zx.platform.utils.PmpUtils;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-7-5 Time: 下午8:09 To
 * change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/mobile/offline")
public class MobileOfflineController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(MobileOfflineController.class);

	public static final String Token = "mapToken";

	@Autowired
	private MerchantOfflineConfigInfoService merchantOfflineConfigInfoService;
	@Autowired
	private OrdLogService ordLogService;
	@Autowired
	private MerchantInfoService merchantInfoService;
	@Autowired
	private AgentInfoService agentInfoService;

	/**
	 * 线下收款
	 *
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String index(String offLineMerchantCode, String mCode, Model model, HttpServletRequest request) {
		try {
			MerchantOfflineConfigInfoModel param = new MerchantOfflineConfigInfoModel();
			param.setMerchantId(offLineMerchantCode);
			param.setOfflinePayId(mCode);
			List<MerchantOfflineConfigInfoModel> offlineConfigInfoModels = merchantOfflineConfigInfoService.getListByModel(param);
			if (null != offlineConfigInfoModels && offlineConfigInfoModels.size() == 1) {
				model.addAttribute("model", offlineConfigInfoModels.get(0));
			} else {
				model.addAttribute("errorMsg", "未开通业务类型");
				return "/jsp/mobile/error";
			}
			return "/jsp/mobile/offline/index";
		} catch (Exception e) {
			model.addAttribute("errorMsg", "系统异常");
			log.error("系统异常", e);
			return "/jsp/mobile/offline/error";
		}
	}

	@RequestMapping("/getOpenId")
	public void getOpenId(HttpServletRequest request,HttpServletResponse response) {
		try {
			String code = request.getParameter("code");
			String openId = WxOauthHelper.getOpenId(code);
			response.getWriter().write(openId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 获取订单二维码
	 *
	 * @param payType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/next")
	public String next(String merchantId, String amount, String code, String payType, Model model,
	                   HttpServletRequest request) {
		try {
			// 将输入金额 转换成 接口需要的单位为分的金额
		    String openId=null;
		/*	if (SUConstants.paymentTypeWX.equals(payType)) {
				if (StrUtils.isBlank(code)){
					model.addAttribute("errorMsg", "获取openId异常");
					log.error("获取openId异常");
					return "/jsp/mobile/offline/error";
				} else {
					openId=WxOauthHelper.getOpenId(code);
				}
				if(StrUtils.isBlank(openId)){
					model.addAttribute("errorMsg", "获取openId异常");
					log.error("获取openId异常");
					return "/jsp/mobile/offline/error";
				}
			}*/
			String orderId = PmpUtils.getPayOrderNum();
			Map map = IncomePayProxy.getOfflineIncomePay(amount, orderId, payType,openId);

			log.info("二维码接口返回信息:" + ToStringBuilder.reflectionToString(map));
			if (null != map && SUConstants.CODE_SUCCESS_VALUE.equals((String) (map.get(SUConstants.CODE_KEY)))) {
				MerchantInfoModel merchantInfoModel = merchantInfoService.getModelByKey(merchantId);
				AgentInfoModel agentInfoModel = agentInfoService.getModelByKey(merchantInfoModel.getAgentId());
				// 保存订单信息
				OrdLogModel ordLogModel = IncomePayProxy
						.transformMerchantToOrdLog(merchantInfoModel, agentInfoModel, payType);
				ordLogModel.setPaymentAmt(Double.valueOf(amount));
				ordLogModel.setOrdId(orderId);
				ordLogService.add(ordLogModel);
				// 返回二维码信息
				Map info = (Map) map.get(SUConstants.INFO_KEY);
				
			
				
				String url = URLDecoder.decode((String) info.get("codeUrl"), "utf-8");
				
				if(SUConstants.paymentTypeAlipay.equals(payType)) {
					url = AlipayUtil.payOrder(orderId, amount, PRODUCT_NAME, merchantId);
				}
				
				return "redirect:" + url;
			} else {
				model.addAttribute("errorMsg", "收款业务出错了");
				log.error("获取二维码异常");
				return "/jsp/mobile/offline/error";
			}
		} catch (Exception e) {
			model.addAttribute("errorMsg", "收款业务出错了");
			log.error("获取二维码异常", e);
			return "/jsp/mobile/offline/error";
		}
	}
	private static final String PRODUCT_NAME="宝数科技合作商户";

	/**
	 * 通知更换
	 *
	 * @param code
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/notify")
	public String notify(String code, Model model, HttpServletRequest request) {
		try {
			String openId = WxOauthHelper.getOpenId(code);
			if (StringUtils.isNotBlank(openId)) {

				model.addAttribute("openId", openId);
				return "/jsp/mobile/offline/notifychange";
			} else {
				model.addAttribute("errorMsg", "账号绑定出错了");
				return "/jsp/mobile/offline/error";
			}
		} catch (Exception e) {
			model.addAttribute("errorMsg", "账号绑定出错了");
			log.error("获取二维码异常", e);
			return "/jsp/mobile/offline/error";
		}
	}

	/**
	 * 通知更换
	 *
	 * @param offlineNotifyChangeDomain
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/notifychange")
	public String notifychange(OfflineNotifyChangeDomain offlineNotifyChangeDomain, Model model,
	                           HttpServletRequest request) {
		try {
			if (StringUtils.isNotBlank(offlineNotifyChangeDomain.getTelephone())) {
				MerchantInfoModel tempMerchant = merchantInfoService.getMerchantInfoModelBySysAccount(offlineNotifyChangeDomain.getTelephone());
				if (null != tempMerchant) {
					MerchantOfflineConfigInfoModel param = new MerchantOfflineConfigInfoModel();
					param.setMerchantId(tempMerchant.getMerchantId());
					param.setPassword(offlineNotifyChangeDomain.getPassword());
					List<MerchantOfflineConfigInfoModel> offlineConfigInfoModels = merchantOfflineConfigInfoService.getListByModel(param);
					if (null != offlineConfigInfoModels && offlineConfigInfoModels.size() == 1) {
						MerchantOfflineConfigInfoModel tempMerchantOfflineConfig = offlineConfigInfoModels.get(0);
						tempMerchantOfflineConfig.setNotifyWxid(offlineNotifyChangeDomain.getOpenId());
						merchantOfflineConfigInfoService.update(tempMerchantOfflineConfig);
						return "/jsp/mobile/offline/result";
					} else {
						model.addAttribute("errorMsg", "账号绑定出错了");
						return "/jsp/mobile/offline/error";
					}
				} else {
					model.addAttribute("errorMsg", "账号绑定出错了");
					return "/jsp/mobile/offline/error";
				}
			} else {
				model.addAttribute("errorMsg", "账号绑定出错了");
				return "/jsp/mobile/offline/error";
			}
		} catch (Exception e) {
			model.addAttribute("errorMsg", "账号绑定出错了");
			log.error("获取二维码异常", e);
			return "/jsp/mobile/offline/error";
		}
	}

	/**
	 * token
	 *
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/token")
	public void token(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String[] ArrTmp = {Token, timestamp, nonce};
		Arrays.sort(ArrTmp);
		StringBuilder sb = new StringBuilder();
		for (String aArrTmp : ArrTmp) {
			sb.append(aArrTmp);
		}
		String pwd = Encrypt(sb.toString());
		String echostr = request.getParameter("echostr");
		log.info("pwd==" + pwd + "  echostr==" + echostr);
		if (pwd.equals(signature)) {
			if (!"".equals(echostr) && echostr != null) {
				response.getWriter().print(echostr);
			}
		}
	}

	public String Encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;
		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); //to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

}
